package file;
import javax.swing.*;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.io.File;

public class FileBrowser extends JFrame {
    private JTree tree;
    public FileBrowser()  {
        setTitle("我的资源管理器");
        setVisible(true);
        setSize(300,600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//发起关闭时默认的执行操作
        setLocation(1400,100);
        DefaultMutableTreeNode root=new DefaultMutableTreeNode("我的电脑");//设置根节点
        tree=new JTree(root);
        tree.addTreeWillExpandListener(new TreeWillExpandListener() {
            //addTreeWillExpandListener是设置监听事件，节点将要被展开
            @Override
            public void treeWillExpand(TreeExpansionEvent event)  {
                TreePath tp=event.getPath();
                DefaultMutableTreeNode node=(DefaultMutableTreeNode)tp.getLastPathComponent();
                Object o=node.getUserObject();
                File file;
                if (o instanceof File){
                    file=(File) o;
                    File[] fs=file.listFiles();
                    if (fs!=null)
                    for (File f:fs){
                        DefaultMutableTreeNode n=new DefaultMutableTreeNode(f);
                        if (f.isDirectory()){
                            DefaultMutableTreeNode cur=new DefaultMutableTreeNode(".");
                            DefaultMutableTreeNode pre=new DefaultMutableTreeNode("..");
                            n.add(cur);
                            n.add(pre);
                        }
                        node.add(n);
                    }
                }
                JOptionPane.showMessageDialog(null,o);
            }

            @Override
            public void treeWillCollapse(TreeExpansionEvent event)  {

            }
        });
        JScrollPane sp=new JScrollPane(tree);
        add(sp);

        File[] fs=File.listRoots();
        for (File file:fs){
            DefaultMutableTreeNode node=new DefaultMutableTreeNode(file);
            if (file.isDirectory()){
                DefaultMutableTreeNode cur=new DefaultMutableTreeNode(".");
                DefaultMutableTreeNode pre=new DefaultMutableTreeNode("..");
                node.add(cur);
                node.add(pre);
            }
            root.add(node);
        }

    }

    public static void main(String[] agrs){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FileBrowser();
            }
        });
    }
}
